<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑作品' : '新增作品'"
    width="600px"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      @submit.prevent
    >
      <el-form-item label="所属艺人" prop="artistId">
        
         <el-select
           v-model="form.artistId"
           placeholder="请选择艺人"
           style="width: 100%"
           :disabled="isEdit"
           @change="handleArtistChange"
           clearable
         >
           <el-option
             v-for="artist in availableArtists"
             :key="artist.id"
             :label="artist.name"
             :value="artist.id"
           >
             <div class="artist-option">
               <span>{{ artist.name }}</span>
             </div>
           </el-option>
         </el-select>

      </el-form-item>

      <el-form-item label="作品标题" prop="title">
        <el-input
          v-model="form.title"
          placeholder="请输入作品标题"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="作品时长" prop="duration">
        <el-input
          v-model="form.duration"
          placeholder="例如: 3:45"
          maxlength="10"
        />
      </el-form-item>

      <el-form-item label="发布日期" prop="releaseDate">
        <el-date-picker
          v-model="form.releaseDate"
          type="date"
          placeholder="选择发布日期"
          style="width: 100%"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>

      <el-form-item label="作品描述" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="4"
          placeholder="请输入作品描述"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="代表作" prop="isRepresentative">
        <el-switch
          v-model="form.isRepresentative"
          active-text="是"
          inactive-text="否"
        />
        <div class="form-tip">
          代表作将在艺人详情页面中优先显示
        </div>
      </el-form-item>

      <!-- 音频管理 (仅编辑模式) -->
      <el-form-item label="音频文件" v-if="isEdit && work">
        <div class="audio-management">
          <div v-if="work.audioUrl" class="current-audio">
            <div class="audio-player-wrapper">
              <div class="audio-info">
                <el-icon class="audio-icon"><Headset /></el-icon>
                <span class="audio-label">当前音频</span>
              </div>
              <audio :src="work.audioUrl" controls preload="none">
                您的浏览器不支持音频播放
              </audio>
            </div>
            <div class="audio-actions">
              <el-button 
                type="primary" 
                size="small" 
                @click="showAudioManager = true"
                :icon="Setting"
              >
                管理音频
              </el-button>
            </div>
          </div>
          <div v-else class="no-audio">
            <div class="upload-placeholder">
              <el-icon class="upload-icon"><Upload /></el-icon>
              <div class="upload-text">
                <span class="primary-text">暂无音频文件</span>
                <span class="secondary-text">点击下方按钮上传音频</span>
              </div>
              <el-button 
                type="primary" 
                size="small" 
                @click="showAudioManager = true"
                :icon="Plus"
                class="upload-btn"
              >
                上传音频
              </el-button>
            </div>
          </div>
        </div>
      </el-form-item>
    </el-form>

    <!-- 音频管理器 -->
    <WorkAudioManager
      v-model="showAudioManager"
      :work="work"
      @success="handleAudioSuccess"
    />

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitting">
        {{ isEdit ? '更新' : '创建' }}
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { Headset, Upload, Plus, Setting } from '@element-plus/icons-vue'
import { createWork, updateWork } from '@/api/work'
import WorkAudioManager from './WorkAudioManager.vue'
import type { Work, Artist } from '@/types'

interface Props {
  modelValue: boolean
  work?: Work | null
  artists: Artist[] | undefined
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 响应式数据
const formRef = ref<FormInstance>()
const submitting = ref(false)
const showAudioManager = ref(false)

// 表单数据
const form = ref({
  artistId: null as number | null,
  title: '',
  duration: '',
  description: '',
  releaseDate: '',
  isRepresentative: false
})



// 处理艺人选择变化
const handleArtistChange = (value: number | null) => {
  form.value.artistId = value
}



// 表单验证规则
const rules: FormRules = {
  artistId: [
    { required: true, message: '请选择艺人', trigger: 'change' }
  ],
  title: [
    { required: true, message: '请输入作品标题', trigger: 'blur' },
    { min: 1, max: 200, message: '标题长度在 1 到 200 个字符', trigger: 'blur' }
  ],
  duration: [
    { pattern: /^(\d{1,2}:)?\d{1,2}:\d{2}$|^\d{1,2}:\d{2}$/, message: '请输入正确的时长格式，如 3:45 或 1:23:45', trigger: 'blur' }
  ],
  description: [
    { max: 500, message: '描述长度不能超过 500 个字符', trigger: 'blur' }
  ]
}

// 计算属性
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const isEdit = computed(() => !!props.work)

// 监听作品数据变化，初始化表单
watch(() => props.work, (work) => {
  if (work) {
    console.log('work', work)
    // 编辑模式
    form.value = {
      artistId: work.artist.id,
      title: work.title,
      duration: work.duration || '',
      description: work.description || '',
      releaseDate: work.releaseDate ? work.releaseDate.split('T')[0] : '',
      isRepresentative: work.isRepresentative
    }
  } else {
    // 新增模式
    form.value = {
      artistId: null,
      title: '',
      duration: '',
      description: '',
      releaseDate: '',
      isRepresentative: false
    }
  }
}, { immediate: true })

// 监听artists变化
watch(() => props.artists, () => {
  // 艺人列表变化时的处理逻辑可以在这里添加
}, { immediate: true })

// 确保artists数据可用的计算属性
const availableArtists = computed(() => {
  return Array.isArray(props.artists) ? props.artists : []
})

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    const submitData = {
      artistId: form.value.artistId!,
      title: form.value.title,
      duration: form.value.duration || null,
      description: form.value.description || null,
      releaseDate: form.value.releaseDate || null,
      isRepresentative: form.value.isRepresentative
    }
    
    if (isEdit.value && props.work) {
      await updateWork(props.work.id, submitData)
      ElMessage.success('更新成功')
    } else {
      await createWork(submitData)
      ElMessage.success('创建成功')
    }
    
    emit('success')
  } catch (error) {
    if (error !== false) { // 不是表单验证错误
      console.error('提交失败:', error)
      ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
    }
  } finally {
    submitting.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  showAudioManager.value = false
  // 重置表单
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 音频管理成功回调
const handleAudioSuccess = () => {
  showAudioManager.value = false
  // 触发父组件更新
  emit('success')
}
</script>

<style lang="scss" scoped>
.artist-option {
  display: flex;
  align-items: center;
  gap: 8px;
  
  span {
    flex: 1;
  }
}

.form-tip {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.audio-management {
  min-width: 450px;
  
  .current-audio {
         .audio-player-wrapper {
       background: #f8f9fa;
       border: 1px solid #e9ecef;
       border-radius: 8px;
       padding: 20px;
       margin-bottom: 12px;
       min-width: 400px;
      
      .audio-info {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 12px;
        
        .audio-icon {
          color: #409eff;
          font-size: 18px;
        }
        
        .audio-label {
          font-weight: 500;
          color: #303133;
          font-size: 14px;
        }
      }
      
             audio {
         width: 100%;
         height: 40px;
         border-radius: 4px;
         min-width: 300px;
       }
    }
    
    .audio-actions {
      text-align: right;
    }
  }
  
  .no-audio {
    .upload-placeholder {
      background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
      border: 2px dashed #c0c4cc;
      border-radius: 12px;
      padding: 32px 24px;
      text-align: center;
      transition: all 0.3s ease;
      
      &:hover {
        border-color: #409eff;
        background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
      }
      
      .upload-icon {
        font-size: 48px;
        color: #c0c4cc;
        margin-bottom: 16px;
        transition: color 0.3s ease;
      }
      
      &:hover .upload-icon {
        color: #409eff;
      }
      
      .upload-text {
        margin-bottom: 20px;
        
        .primary-text {
          display: block;
          font-size: 16px;
          font-weight: 500;
          color: #606266;
          margin-bottom: 8px;
        }
        
        .secondary-text {
          display: block;
          font-size: 14px;
          color: #909399;
        }
      }
      
      .upload-btn {
        min-width: 120px;
        height: 36px;
        font-size: 14px;
        border-radius: 18px;
        box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
        transition: all 0.3s ease;
        
        &:hover {
          transform: translateY(-1px);
          box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
        }
      }
    }
  }
}
</style>
